package com.loongtech.bi.action.system;

import com.loongtech.bi.entity.system.EntitySysModel;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.manager.system.SysModelManager;
import com.loongtech.bi.support.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 模块注册
 * 
 * @author xckuang
 * @date 2014-10-06
 */
@Controller("modelRegisterAction")
@Scope("view")
public class ModelRegisterAction implements Serializable {
	private static final long serialVersionUID = 1L;
	@Autowired
	private Session session;
	@Autowired
	private SysModelManager sysModelManager;
	@Autowired
	private SysLogManager sysLogManager;
	private EntitySysModel model;
	private Map<Integer, EntitySysModel> modelMap;

	@Autowired
	public void init() {
		setModel(new EntitySysModel());
		modelMap = new HashMap<Integer, EntitySysModel>();
		EntitySysModel all = new EntitySysModel();
		all.setId(0);
		all.setDescription("根目录");
		modelMap.put(all.getId(), all);
		for(EntitySysModel domain : sysModelManager.findAll()) {
			modelMap.put(domain.getId(), domain);
		}
	}

	public void add() {
		FacesContext context = FacesContext.getCurrentInstance();

		// 判断参数
		String name = model.getName();
		if(null == name || name.isEmpty()) {
			context.addMessage(null, new FacesMessage("增加模块失败", "模块名为空!"));
			return;
		}
		int fatherId = model.getFatherId();
		if(fatherId > 0 && null == sysModelManager.get(fatherId)) {
			context.addMessage(null, new FacesMessage("增加模块失败", "父模块为空!"));
			return;
		}
		// 判断用户name是否已经被注册
		if(null != sysModelManager.getBy("name", name)) {
			context.addMessage(null, new FacesMessage("增加模块失败", "模块名称已存在!"));
			return;
		}
		// 注册模块
		try {
			sysModelManager.persist(model);
			context.addMessage(null, new FacesMessage("增加模块成功", "模块名称为" + name));
			sysLogManager.addLog(session.getUserName(), "增加模块成功" + name);
			setModel(new EntitySysModel());
		} catch(Exception ex) {
			context.addMessage(null, new FacesMessage("增加模块失败", "注册时发生异常!"));
		}
	}

	public EntitySysModel getModel() {
		return model;
	}

	public void setModel(EntitySysModel model) {
		this.model = model;
	}

	public Map<Integer, EntitySysModel> getModelMap() {
		return modelMap;
	}

	public void setModelMap(Map<Integer, EntitySysModel> modelMap) {
		this.modelMap = modelMap;
	}
}
